<?php
namespace admin\controllers;

use yii\web\Controller;
use yii\helpers\ArrayHelper;
use yii\filters\auth\QueryParamAuth;
use common\helpers\ErrorHelper;
use common\helpers\ShowJson;
use admin\models\user\LoginForm;
use admin\models\user\User;
use yii\filters\AccessControl;

class SsoController extends Controller
{
    public $layout = false;
    
    /*public function behaviors()
    {
        return ArrayHelper::merge (parent::behaviors(), [
            'authenticator' => [
                'class' => QueryParamAuth::className(),
                // 跳过auth认证的控制器
                'optional' => [
                    'login',
                    'loginsave',
                    'register',
                    'registersave',
                    'logout'
                ],
            ]
        ] );
    }*/
    
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'loginsave', 'register', 'registersave'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    
    public function actionLogin()
    {
        return $this->render("login");
    }
    
    
    /**
     * 登录
     * @param string $account   手机号
     * @param string $password  原始密码
     * @return json             通行证信息
     */
    public function actionLoginsave()
    {
        $error = ErrorHelper::get('loginError');
        $model = new LoginForm();
        if ($model->load(\Yii::$app->request->post())) {
            // 登录成功后，返回login_token
            $userModel = $model->login();
            if (empty($userModel)) {
                $error['message'] = "账号或密码错误";
                throw new \Exception($error['message']);
            }
            $userInfo = $userModel->attributes;
            $this->redirect("/default");
        } else {
            // 参数错误
            $paramsError = ErrorHelper::get('paramsError');
            throw new \Exception($paramsError['message']);
        }
    }
    
    
    public function actionRegister()
    {
        return $this->render("register");
    }
    
    
    /**
     * 注册
     * @param string username       账号
     * @param string password       原始密码
     * @return json                 通行证和用户详情信息
     */
    public function actionRegistersave()
    {
        $username = trim(\Yii::$app->request->post("username", ''));
        $password = trim(\Yii::$app->request->post("password", ''));
        $repeatPassword = trim(\Yii::$app->request->post("repeat_password", ''));
        $registerError = ErrorHelper::get('registerError');
        if(empty($username) || empty($password) || empty($repeatPassword)){
            $registerError['message'] = "请正确填写账号和密码";
            ShowJson::showErrorJson($registerError);
        }
        if ($password != $repeatPassword) {
            $registerError['message'] = "两次密码不一致";
            ShowJson::showErrorJson($registerError);
        }
        
        // 检测登录名是否存在
        $userInfo = \Yii::$app->adminUserComponent->getUserInfoByColumn('username', $username);
        if (!empty($userInfo)) {
            // 已被注册
            $registerError['message'] = '该账号已被注册';
            ShowJson::showErrorJson($registerError);
        }
        
        $passportUserInfoObj = \Yii::$app->adminUserComponent->createUser($username, $password);
        if (empty($passportUserInfoObj)) {
            $registerError['message'] = '注册失败';
            ShowJson::showErrorJson($registerError);
        }
        
        ShowJson::showSuccessJson();
    }
    
    public function actionLogout()
    {
        \Yii::$app->user->logout();
        $this->redirect("/sso/login");
    }
}